package com.itboye.hutouben.activity.luntan;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itboye.hutouben.R;
import com.itboye.hutouben.activity.login.LoginActivity;
import com.itboye.hutouben.adapter.HuiFuTwodapter;
import com.itboye.hutouben.base.ptr.BasePtr;
import com.itboye.hutouben.bean.HuiFuTwoBean;
import com.itboye.hutouben.presenter.LunTanPresenter;
import com.itboye.hutouben.util.BaseOtherActivity;
import com.itboye.hutouben.util.ByAlert;
import com.itboye.hutouben.util.Const;
import com.itboye.hutouben.util.GlideLoader;
import com.itboye.hutouben.util.IsUtilUid;
import com.itboye.hutouben.util.MyGongJv;
import com.itboye.hutouben.util.MyListView;
import com.itboye.hutouben.volley.ResultEntity;
import com.itboye.hutouben.widget.InputMethodLayout;
import com.itboye.hutouben.widget.chatemoji.FaceInputView;
import com.itboye.hutouben.widget.chatemoji.Spanned2String;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

import static com.itboye.hutouben.util.SPUtils.getSp;

/**
 * 帖子回复
 */
public class TieziHuiFuActivity extends BaseOtherActivity implements Observer, HuiFuTwodapter.ClickListener {
    ImageView close_icon;
    TextView add_shap_title_tv;
    InputMethodLayout root_pinglun;
    PtrFrameLayout commend_anchor_ptr;
    MyListView list_pinglun;
    ImageView img_head;
    TextView txt_title, txt_time, txt_content;
    TextView fasong;
    EditText et_huifu;
    String id, pid;
    String uid;
    HuiFuTwoBean huiFuBean;
    List<HuiFuTwoBean.RepeatInfoEntity> listBean;
    int size = 1;
    int page = 10;
    TextView chakan_yuan;
    LunTanPresenter lunTanPresenter;

    HuiFuTwodapter adapter;

    int type = 1;//来标记是回复 1 回复  2回复下级列表
    int pinglunPosition;//评论的是哪一条
    int fuid;

    private Dialog dialog;// 自定义Dialog
    int deleteRid;

    ImageView emoji;//表情按钮

    LinearLayout faceInputContainer;//表情显示布局
    private FaceInputView faceInputView;//表情

    @Override
    protected int layout_id() {
        return R.layout.activity_tizi_guifu;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {
        root_pinglun = (InputMethodLayout) findViewById(R.id.root_pinglun);
        root_pinglun.setOnkeyboarddStateListener(new InputMethodLayout.onKeyboardsChangeListener() {// 监听软键盘状态
            @Override
            public void onKeyBoardStateChange(int state) {
                // TODO Auto-generated method stub
                switch (state) {
                    case InputMethodLayout.KEYBOARD_STATE_SHOW:
                        //  Toast.makeText(ToPicDetailActivity.this, "打开软键盘", 1000).show();
                        break;
                    case InputMethodLayout.KEYBOARD_STATE_HIDE:
                        //  Toast.makeText(ToPicDetailActivity.this, "关闭软键盘", 1000).show();
                        if (faceInputContainer.getVisibility() != View.VISIBLE) {
                            type = 1;
                            et_huifu.setText("");
                            et_huifu.setHint("回复评论");
                        }
                        break;
                }
            }
        });
        BasePtr.setPagedPtrStyle(commend_anchor_ptr);
        lunTanPresenter = new LunTanPresenter(this);
        huiFuBean = new HuiFuTwoBean();
        listBean = new ArrayList<>();
        pid = getIntent().getStringExtra("pid");
        id = getIntent().getStringExtra("id");
        uid = getSp(this, Const.ID);
        showExtraDialog();
        showProgressDialog("加载数据,请稍后...", true);
        lunTanPresenter.topicHuiFuListTwo(uid, pid + "", id + "", size, page);

        adapter = new HuiFuTwodapter(TieziHuiFuActivity.this, listBean, fuid, this);
        list_pinglun.setAdapter(adapter);
        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                size++;
                lunTanPresenter.topicHuiFuListTwo(uid, pid + "", id + "", size, page);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                lunTanPresenter.topicHuiFuListTwo(uid, pid + "", id + "", size, page);
            }
        });
        commend_anchor_ptr.autoRefresh(true);

        list_pinglun.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (uid.equals(String.valueOf(listBean.get(position).getUid()))) {
                    deleteRid = listBean.get(position).getId();
                    dialog.show();
                }
            }
        });

        faceInputView = new FaceInputView(this);
        faceInputContainer.addView(faceInputView);
        faceInputView.setOnClickListener(new FaceInputListenr());
    }

    private class FaceInputListenr implements FaceInputView.OnFaceClickListener {
        @Override
        public void selectedFace(FaceInputView.Face face) {
            int id = face.faceId;
            if (id == R.drawable.ic_face_delete_normal)// 删除按钮
            {
                int index = et_huifu.getSelectionStart();
                if (index == 0)
                    return;
                Editable editable = et_huifu.getText();
                editable.delete(index - 1, index);// 删除最后一个字符或表情
            } else {
                et_huifu.append(Html.fromHtml("<img src='" + id + "'/>",
                        imageGetter, null));// 添加表情
            }
        }
    }

    // 输入表情需要
    Html.ImageGetter imageGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            int id = Integer.parseInt(source);
            @SuppressWarnings("deprecation")
            Drawable d = getResources().getDrawable(id);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            return d;
        }
    };

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.emoji:
                if (faceInputContainer.getVisibility() == View.VISIBLE) {
                    faceInputContainer.setVisibility(View.GONE);
                    emoji.setBackgroundResource(R.drawable.emoji);
                } else {
                    faceInputContainer.setVisibility(View.VISIBLE);
                    emoji.setBackgroundResource(R.drawable.jianpan);
                }
                MyGongJv.yincang(v);
                break;

            case R.id.et_huifu:
                if (faceInputContainer.getVisibility() == View.VISIBLE) {
                    faceInputContainer.setVisibility(View.GONE);
                    emoji.setBackgroundResource(R.drawable.emoji);
                }
                break;
            case R.id.chakan_yuan:
            case R.id.close_icon:
                finish();
                break;
            case R.id.fasong:
                faceInputContainer.setVisibility(View.GONE);
                if (IsUtilUid.isUid() == null || IsUtilUid.isUid() == "") {
                    Intent intent1 = new Intent(TieziHuiFuActivity.this, LoginActivity.class);
                    startActivity(intent1);
                    return;
                }
                String content = et_huifu.getText().toString().trim();
                if (content.equals("")) {
                    ByAlert.alert("请输入回复内容");
                    return;
                }
                showProgressDialog("正在发表,请稍后...", true);
                MyGongJv.yincang(v);
                if (type == 1) {
                    lunTanPresenter.huifuTieZi(uid, huiFuBean.getPid() + "", huiFuBean.getId() + "", huiFuBean.getUid() + "", Spanned2String.parse(et_huifu.getText()), "", Const.APP_FOR);
                } else {
                    lunTanPresenter.huifuTieZi(uid, listBean.get(pinglunPosition).getPid() + "", listBean.get(pinglunPosition).getRid() + "", listBean.get(pinglunPosition).getUid() + "", Spanned2String.parse(et_huifu.getText()), "", Const.APP_FOR);
                }
                type = 1;
                et_huifu.setText("");
                et_huifu.setHint("回复评论");
                break;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            //帖子回复列表
            if (entity.getEventType() == LunTanPresenter.huifu_two_success) {
                commend_anchor_ptr.refreshComplete();

                huiFuBean = (HuiFuTwoBean) entity.getData();
                fuid = huiFuBean.getUid();
                add_shap_title_tv.setText("共" + huiFuBean.getReplys_count() + "条回复");
                txt_title.setText(huiFuBean.getUname());
                txt_time.setText(huiFuBean.getCreate_time_desc());
                txt_content.setText(huiFuBean.getContent());
//                XImageLoader.load(Const.IMAGE_HEAD_TWO + huiFuBean.getUid(),
//                        img_head);
                GlideLoader.displayImageHeadCircular(TieziHuiFuActivity.this, huiFuBean.getUid() + "", img_head);
                if (size == 1) {
                    listBean.clear();
                }
                if (huiFuBean != null) {
                    listBean.addAll(huiFuBean.getReplys_info());
                    adapter = new HuiFuTwodapter(TieziHuiFuActivity.this, listBean, fuid, this);
                    list_pinglun.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                }

            } else if (entity.getEventType() == LunTanPresenter.huifu_two_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == LunTanPresenter.huifu_tiezi_success) {//帖子回复
                ByAlert.alert(entity.getData());
                lunTanPresenter.topicHuiFuListTwo(uid, pid + "", id + "", size, page);
                adapter.notifyDataSetChanged();
            } else if (entity.getEventType() == LunTanPresenter.huifu_tiezi_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == LunTanPresenter.delete_pinglun_success) {//删除自己的评论
                lunTanPresenter.topicHuiFuListTwo(uid, pid + "", id + "", size, page);
                adapter.notifyDataSetChanged();

            } else if (entity.getEventType() == LunTanPresenter.delete_pinglun_fail) {
                ByAlert.alert(entity.getData());
            }
        }
    }

    //每条评论的回复
    @Override
    public void pinglun(View v) {
        if (IsUtilUid.isUid() == null || IsUtilUid.isUid() == "") {
            Intent intent1 = new Intent(TieziHuiFuActivity.this, LoginActivity.class);
            startActivity(intent1);
            return;
        }
        pinglunPosition = (Integer) v.getTag();
        type = 2;
        et_huifu.setHint("回复:" + listBean.get(pinglunPosition).getUname());

        MyGongJv.xianshi();
        et_huifu.requestFocus();
    }


    /**
     * 删除Dialog
     */
    private void showExtraDialog() {
        dialog = new Dialog(this, R.style.rel_dialog);
        View view = LayoutInflater.from(this).inflate(
                R.layout.dialog_delete, null);
        dialog.setContentView(view);

        TextView dialog_ok = (TextView) view.findViewById(R.id.dialog_ok);
        TextView dialog_quxiao = (TextView) view.findViewById(R.id.dialog_quxiao);
        TextView user_title = (TextView) view.findViewById(R.id.user_title);
        TextView dialog_conext = (TextView) view.findViewById(R.id.dialog_conext);
        user_title.setText("删除回复");
        dialog_conext.setText("确定删除此回复？");

        dialog.setCanceledOnTouchOutside(false);
        dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
                showProgressDialog("刪除中,请稍后...", false);
                // presenter.deleteMessOne(IsUtilUid.isUid(),"6221",deleteId);
                lunTanPresenter.deleteMyHuiFu(uid, deleteRid);
            }
        });
        dialog_quxiao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        int screenWidth = display.getWidth();
        // 屏幕高度
        int screenHeight = display.getHeight();
        Window window = dialog.getWindow();

        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        lp.width = screenWidth * 3 / 4;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }
}
